package cn.jdemo.ref.WeakReference;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Demo03 {
    public static void main(String[] args) throws InterruptedException {
        test2();
    }

    /**
     * 输出:
     * put success
     * get 777
     */
    private static void test() throws InterruptedException {
        Map<WeakReference<Integer>, Integer> map = new HashMap<>(8);
        WeakReference<Integer> key = new WeakReference<>(666);
        map.put(key,777);
        System.out.println("put success");
        Thread.sleep(1000);
        System.gc();
        System.out.println("get " + map.get(key));
    }

    /**
     * 输出:
     * put success
     * get null
     */
    private static void test1() throws InterruptedException {
        Map<WeakReference<Integer>, WeakReference<Integer>> map = new HashMap<>(8);
        WeakReference<Integer> key = new WeakReference<>(666);
        WeakReference<Integer> value = new WeakReference<>(777);
        map.put(key,value);
        System.out.println("put success");
        Thread.sleep(1000);
        System.gc();
        System.out.println("get " + map.get(key).get());
    }

    /**
     * 输出:
     * put success
     * get 2
     */
    private static void test2() throws InterruptedException {
        Map<WeakReference<Integer>, WeakReference<Integer>> map = new HashMap<>(8);
        // 注意这里~
        WeakReference<Integer> key = new WeakReference<>(1);
        WeakReference<Integer> value = new WeakReference<>(2);
        map.put(key,value);
        System.out.println("put success");
        Thread.sleep(1000);
        System.gc();
        System.out.println("get " + map.get(key).get());
    }
}
